package com.tledu.xpath;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.FileInputStream;
import java.io.IOException;

public class XPath02 {
    private static Document document;
    private static XPath xPath;

    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
        init();


    }

    public static void init() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
        // 1. 初始化
        //      1.1 初始化Document对象。 Document对应的就是要解析的文档(对于初始化的过程，大家不需要背下来)
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // 不进行校验
        documentBuilderFactory.setValidating(false);
        // 创建了这个对象之后，就可以读取xml文件，获取Document
        DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();
        // 读取到对应的文件. 这个对象就承载xml数据
        document = db.parse(new FileInputStream("F:\\生产实习\\数据可视化\\demo\\webMagic-19\\src\\main\\resources\\rss.xml"));
        //      1.2 初始化xpath
        XPathFactory xPathFactory = XPathFactory.newInstance();
        // 创建xpath，后续就可以通过xpath解析对应的xml文档了
        xPath = xPathFactory.newXPath();
        getStudentByAge();
        getBookByPrice(30.0,"<");
    }

    /**
     * 根据年龄获取学生
     * 1. 获取到年龄大于20岁的学生的姓名
     * 2. 获取价格小于30的书的名字
     * 3. 获取所有链接的地址
     * //     * @param age
     * //     * @param symbol
     */
    public static void getStudentByAge() throws XPathExpressionException {
        // 属性比较，用@进行比较
        NodeList nodeList = (NodeList) xPath.evaluate("//student[@age > 20]", document, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getAttributes().getNamedItem("name").getNodeValue());
        }
    }

    /**
     * 根据价格进行book的筛选
     * 获取价格小于30的书的名字
     * @param price  价格
     * @param symbol 符号
     */
    public static void getBookByPrice(double price, String symbol) throws XPathExpressionException {
        String expression = "//book[price "+symbol+" "+price+"]/title/text()";
        System.out.println(expression);
        // 属性比较，用@进行比较
        NodeList nodeList = (NodeList) xPath.evaluate(expression, document, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getNodeValue());
        }
    }
}
